package com.feifan.monthhelper.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.db.DayRecordBean;
import com.feifan.monthhelper.calculate.CalculateUtils;
import com.feifan.monthhelper.calendar.CalendarUtils;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.db.DBUtls;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.ui.dialog.CommonDialog;
import com.feifan.monthhelper.utils.CalendarAlarmUtils;
import com.feifan.monthhelper.utils.CleanDataUtils;
import com.feifan.monthhelper.utils.CommonDialogUtils;
import com.feifan.monthhelper.utils.SPUtils;
import com.feifan.monthhelper.wedget.DoubleClickListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cn.qqtheme.framework.picker.OptionPicker;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.feifan.monthhelper.bao.App.getContext;

public class MineActivity extends BaseActivity {

    private static final int REQUEST_CALENDAR = 123;
    @BindView(R.id.rl_title)
    View rlTitle;

    TimePickerView pvTime;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.ll_statistical)
    LinearLayout llStatistical;
    @BindView(R.id.ll_menstrual_period)
    LinearLayout llMenstrualPeriod;
    @BindView(R.id.ll_menstrual_span)
    LinearLayout llMenstrualSpan;
    @BindView(R.id.ll_alarm)
    LinearLayout llAlarm;
    @BindView(R.id.tv_cache_memory)
    TextView tvCacheMemory;
    @BindView(R.id.ll_clean_cache)
    LinearLayout llCleanCache;
    @BindView(R.id.iv_add)
    ImageView ivAdd;
    @BindView(R.id.tv_menstrual_period_days)
    TextView tvMenstrualPeriodDays;
    @BindView(R.id.tv_menstrual_span_days)
    TextView tvMenstrualSpanDays;
    @BindView(R.id.tv_alarm_day)
    TextView tvAlarmDay;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;

    private List<String> mensesSperiodDays;
    private List<String> mensesSpanDays;
    private List<String> alarmDays;
    //数据是否更新
    private boolean update;

    private OptionPicker.OnOptionPickListener optionPickListener = new OptionPicker.OnOptionPickListener() {
        @Override
        public void onOptionPicked(int index, String item) {
            if (tvMenstrualSpanDays != null) {
                tvMenstrualSpanDays.setText(item);
            }
            if (item.equals(SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS)))
                return;
            SPUtils.getInstance().put(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS, item);
            updateCalculateData();
            update = true;
        }
    };

    private OptionPicker.OnOptionPickListener mensesSperiodPickListener = new OptionPicker.OnOptionPickListener() {
        @Override
        public void onOptionPicked(int index, String item) {
            if (tvMenstrualPeriodDays != null) {
                tvMenstrualPeriodDays.setText(item);
            }
            if (item.equals(SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_DAYS)))
                return;
            SPUtils.getInstance().put(Constant.ShareKey.MENSTRUAL_CYCLE_DAYS, item);
            updateCalculateData();
            update = true;
        }
    };

    private OptionPicker.OnOptionPickListener alarmPickListener = new OptionPicker.OnOptionPickListener() {
        @Override
        public void onOptionPicked(int index, String item) {
            if (tvAlarmDay != null) {
                tvAlarmDay.setText(item);
            }
            SPUtils.getInstance().put(Constant.ShareKey.ALARM_TIME, item);

            List<DayRecordBean> dayRecordBeans = DBUtls.queryDayRecordBy(CalendarUtils.getDay(new Date(), 0), CalendarUtils.getDay(new Date(), 50));
            for(DayRecordBean recordBean : dayRecordBeans) {
                if(recordBean.state == Constant.MenstrualState.CACULATE_MENSTRUAL_DAY) {
                    System.out.println("aaa = " + GsonUtils.toJson(recordBean));
                    long startDate = recordBean.createDate.getTime();
                    if(index == 1) {
                        startDate -=  86400000;
                    } else if(index == 2) {
                        startDate -= 86400000 * 3;
                    } else if(index == 3) {
                        startDate -= 86400000 * 7;
                    }
                    //对当前时间求余86400000（一天的时间），就是当前的时分秒
                    insertCalendar(startDate + System.currentTimeMillis()%86400000);
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {
    }

    @Override
    public void finish() {
        if (update) {
            setResult(RESULT_OK);
        }
        super.finish();
    }

    @Override
    protected void initView() {
        tvMenstrualPeriodDays.setText(SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_DAYS));
        tvMenstrualSpanDays.setText(SPUtils.getInstance().getString(Constant.ShareKey.MENSTRUAL_CYCLE_SPAN_DAYS));
        tvAlarmDay.setText(SPUtils.getInstance().getString(Constant.ShareKey.ALARM_TIME, "不提前"));

        llMenstrualPeriod.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                initMensesSperiodDays();
                CommonDialogUtils.ShowOptionPicker(MineActivity.this, mensesSperiodDays, tvMenstrualPeriodDays.getText().toString().trim(), mensesSperiodPickListener);
            }
        });

        llMenstrualSpan.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                initMensesSpanDays();
                CommonDialogUtils.ShowOptionPicker(MineActivity.this, mensesSpanDays, tvMenstrualSpanDays.getText().toString().trim(), optionPickListener);
            }
        });

        llAlarm.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                fetchPermission(REQUEST_CALENDAR);
            }
        });

        llStatistical.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                startActivity(new Intent(MineActivity.this, MenstrualStatisticsActivity.class));
            }
        });
        llCleanCache.setOnClickListener(view -> {
            showClearCacheDialog();
        });
        llFeedback.setOnClickListener(new DoubleClickListener() {
            @Override
            public void doOnClick(View view) {
                startActivity(new Intent(MineActivity.this, FeedbackActivity.class));
            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        try {
            String totalCacheSize = CleanDataUtils.getTotalCacheSize(this);
            tvCacheMemory.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showAlarmWheel() {
        alarmDays = Arrays.asList(getResources().getStringArray(R.array.alarm_strings));
        CommonDialogUtils.ShowOptionPicker(MineActivity.this, alarmDays, tvAlarmDay.getText().toString().trim(), alarmPickListener);
    }

    //计算并更新数据库
    private void updateCalculateData() {
        Disposable disposable = Observable.create(emitter -> {
            emitter.onNext(CalculateUtils.calculateAndUpdateToDb(DBUtls.getAllDayRecord(), DBUtls.queryAllMenstrualRecord()));
            emitter.onComplete();
        })
                .doOnSubscribe(d -> showLoadingDialog("更新数据中..."))
                .doOnError(o -> dismisDialog())
                .doOnComplete(() -> dismisDialog())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                });
        addDisposable(disposable);
    }

    private void showClearCacheDialog() {
        CommonDialog.Builder commonDialogBuilder = new CommonDialog.Builder(MineActivity.this);
        commonDialogBuilder.setTitle(getResources().getString(R.string.are_you_clear_cache))
                .setLeftText(getResources().getString(R.string.ok))
                .setRightText(getResources().getString(R.string.cancel))
                .setListener(buttonPos -> {
                    if (buttonPos == CommonDialog.CLICK_POS_LEFT) {
                        //清除缓存
                        CleanDataUtils.clearAllCache(getContext());
                        String clearSize = CleanDataUtils.getTotalCacheSize(getContext());
                        tvCacheMemory.setText(clearSize);
                        DBUtls.deleteAllDayRecord(DBUtls.getAllDayRecord());
                        DBUtls.deleteAllMenstrualRecord(DBUtls.queryAllMenstrualRecord());
                        SPUtils.getInstance().put(Constant.ShareKey.BIRTHDAY, "");
                    }
                });
        commonDialogBuilder.show();
    }

    private void initMensesSpanDays() {
        if (mensesSpanDays == null) {
            mensesSpanDays = new ArrayList<>();
            for (int i = 20; i < 41; i++) {
                mensesSpanDays.add(i + "天");
            }
        }
    }

    private void initMensesSperiodDays() {
        if (mensesSperiodDays == null) {
            mensesSperiodDays = new ArrayList<>();
            for (int i = 1; i < 11; i++) {
                mensesSperiodDays.add(i + "天");
            }
        }
    }

    public void fetchPermission(int requestCode) {
        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return;
        }

        // 如果有授权，走正常插入日历逻辑
        if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
            showAlarmWheel();
        } else {
            // 如果没有授权，就请求用户授权
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CALENDAR,
                    Manifest.permission.READ_CALENDAR}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CALENDAR) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户同意的授权请求
                showAlarmWheel();
            } else {
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_CALENDAR)) {
                    // 如果用户不是点击了拒绝就跳转到系统设置页
                    CommonDialog.Builder commonDialogBuilder = new CommonDialog.Builder(MineActivity.this);
                    commonDialogBuilder.setTitle(getResources().getString(R.string.set_calendar_permission))
                            .setLeftText(getResources().getString(R.string.cancel))
                            .setRightText(getResources().getString(R.string.ok))
                            .setListener(buttonPos -> {
                                if (buttonPos == CommonDialog.CLICK_POS_LEFT) {
                                    //清除缓存
                                    gotoSettings();
                                }
                            });
                    commonDialogBuilder.show();
                }
            }
        }
    }

    private void gotoSettings() {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        startActivity(intent);
    }

    private void insertCalendar(long startTime) {
        CalendarAlarmUtils.deleteCalendarEventRemind(getContext(), "月经提醒", "月经预计即将来临！", null);
        CalendarAlarmUtils.addCalendarEventRemind(getContext(), "月经提醒", "月经预计即将来临！", startTime, startTime + 5 * 60 * 1000, 0, new CalendarAlarmUtils.onCalendarRemindListener() {
            @Override
            public void onFailed(Status error_code) {
                ToastUtils.showShort("提醒设置失败！");
            }

            @Override
            public void onSuccess() {
                ToastUtils.showShort("提醒设置成功！");
            }
        });
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_mine;
    }
}
